package cool.doudou.doudada.wechat.core.processor;

import cool.doudou.doudada.wechat.annotation.WechatNotify;
import cool.doudou.doudada.wechat.core.factory.MethodFactory;
import cool.doudou.doudada.wechat.core.method.NotifyMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.Arrays;

/**
 * WechatNotifyBeanPostProcessor
 *
 * @author jiangcs
 * @since 2022/2/20
 */
@Slf4j
public class WechatNotifyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Arrays.stream(bean.getClass().getDeclaredMethods())
                .filter(method -> method.isAnnotationPresent(WechatNotify.class))
                .forEach(method -> {
                    if (method.getReturnType() != boolean.class) {
                        log.error("@WechatNotify annotated method must return boolean, but is : {}", method.getReturnType());
                        return;
                    }

                    if (MethodFactory.getNotify() != null) {
                        log.error("there are multiple @WechatNotify annotations");
                        return;
                    }

                    MethodFactory.setNotify(NotifyMethod.builder().bean(bean).method(method).build());
                });
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
